package org.shj.netty.chartper11;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class WebSocketServer {
	
	public void run(final int port) throws Exception{
		//配置服务端的NIO线程组
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try{
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
			 .channel(NioServerSocketChannel.class)
			 .handler(new LoggingHandler(LogLevel.INFO))
			 .childHandler(new ChannelInitializer<SocketChannel>(){
				 protected void initChannel(SocketChannel channel) throws Exception{
					 ChannelPipeline pipeline = channel.pipeline();
					 pipeline.addLast("http-codec", new HttpServerCodec());
					 pipeline.addLast("http-aggregator", new HttpObjectAggregator(65536));
					 pipeline.addLast("http-chunked", new ChunkedWriteHandler());
					 pipeline.addLast("handler", new WebSocketServerHandler());
					
				}
			 });
			
			//绑定端口， 同步等待成功
			Channel ch = b.bind(port).sync().channel();
			System.out.println("Web socket server started at port: " + port + ". Open http://localhost:" + port + "/");
			
			//等待服务端监听端口关闭
			ch.closeFuture().sync();
		}finally{
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
		
	public static void main(String[] args) throws Exception{
		int port = 8080;
		if(args != null && args.length > 0){
			try{
				port = Integer.valueOf(args[0]);
			}catch(NumberFormatException e){
				
			}
		}
		
		new WebSocketServer().run(port);
	}
}
